import "./reset.css";
import roleForm from "../form/role.vue";
import editForm from "../form/index.vue";
import { message } from "@/utils/message";
import { addDialog } from "@/components/ReDialog";
import type { PaginationProps } from "@pureadmin/table";
import { ElMessageBox } from "element-plus";
import { computed, onMounted, reactive, ref, type Ref, h } from "vue";
import { http } from "@/utils/http";
import { changeHttpLink } from "@/utils/test";
import type { FormItemProps } from "./types";

// 导出 useDeviceCorrelatedHooks 函数
export function useDeviceCorrelatedHooks() {
  return {
    treeProps: {
      children: "children",
      label: "label"
    },
    switchStyle: ref({
      width: "58px",
      height: "30px"
    })
  };
}

export function useDeviceCorrelated(tableRef: Ref) {
  const form = reactive({
    deptId: "",
    deviceName: "",
    correlatedDevice: "",
    status: "",
    OrderBy: "",
    SearchTerm: ""
  });
  const formRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  const selectedNum = ref(0);
  const higherDeptOptions = ref([]);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "勾选列",
      type: "selection",
      fixed: "left",
      reserveSelection: true
    },
    {
      label: "ID",
      prop: "id",
      width: 90
    },
    {
      label: "主设备名称",
      prop: "deviceName",
      minWidth: 130
    },
    {
      label: "主设备类型",
      prop: "deviceType",
      minWidth: 130
    },
    {
      label: "关联设备ID",
      prop: "correlatedDeviceId",
      minWidth: 90
    },
    {
      label: "关联设备名称",
      prop: "correlatedDeviceName",
      minWidth: 130
    },
    {
      label: "关联设备类型",
      prop: "correlatedDeviceType",
      minWidth: 130
    },
    {
      label: "关联状态",
      prop: "correlatedStatus",
      width: 90,
      formatter: (row: any) => {
        return row.status === 1 ? "已启用" : "已停用";
      }
    },
    {
      label: "租户ID",
      prop: "tenantId",
      width: 90
    },
    {
      label: "租户名称",
      prop: "tenantName",
      minWidth: 130
    },
    {
      label: "经销商ID",
      prop: "dealerId",
      width: 90
    },
    {
      label: "经销商名称",
      prop: "dealerName",
      minWidth: 130
    },
    {
      label: "创建时间",
      prop: "createTime",
      width: 180
    },
    {
      label: "操作",
      fixed: "right",
      width: 180,
      slot: "operation"
    }
  ];
  const buttonClass = computed(() => {
    return [
      "h-[20px]!",
      "reset-margin",
      "text-gray-500!",
      "dark:text-white!",
      "dark:hover:text-primary!"
    ];
  });

  // 加载表格数据
  function loadTableData() {
    loading.value = true;
    const params = {
      ...form,
      page: pagination.currentPage,
      pageSize: pagination.pageSize
    };

    http
      .get(changeHttpLink("index.php/device/deviceCorrelated/index"), {
        params
      })
      .then((res: any) => {
        if (res.status === "success") {
          dataList.value = res.Data.Items;
          pagination.total = res.Data.TotalCount;
        } else {
          message(res.Message, { type: "error" });
        }
        loading.value = false;
      })
      .catch(err => {
        message(err.message, { type: "error" });
        loading.value = false;
      });
  }

  // 搜索
  function onSearch() {
    pagination.currentPage = 1;
    loadTableData();
  }

  // 重置表单
  function resetForm(formEl: any) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }

  // 批量删除
  function onbatchDel() {
    const selection = tableRef.value?.getSelectionRows() || [];
    if (selection.length === 0) {
      message("请选择要删除的记录", { type: "warning" });
      return;
    }

    const ids = selection.map((item: any) => item.id).join(",");

    ElMessageBox.confirm(
      `确认要删除选中的${selection.length}条记录吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    )
      .then(() => {
        http
          .post(
            changeHttpLink(
              "index.php/device/deviceCorrelated/deviceCorrelated_delete"
            ),
            {
              data: { ids }
            }
          )
          .then((res: any) => {
            if (res.status === "success") {
              message("删除成功", { type: "success" });
              onSearch();
              tableRef.value?.clearSelection();
            } else {
              message(res.Message, { type: "error" });
            }
          })
          .catch(err => {
            message(err.message, { type: "error" });
          });
      })
      .catch(() => {
        // 取消操作
      });
  }

  // 打开对话框
  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}设备关联`,
      props: {
        formInline: {
          title,
          higherDeptOptions: higherDeptOptions.value,
          ...row
        }
      },
      width: "46%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(
            `您${title}了设备关联名称为${curData.form.deviceName || curData.form.correlatedDevice}的这条数据`,
            {
              type: "success"
            }
          );
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(valid => {
          if (valid) {
            console.log("curData", curData);
            // 表单规则校验通过
            if (title === "新增") {
              // 实际开发先调用新增接口，再进行下面操作
              chores();
            } else {
              // 实际开发先调用修改接口，再进行下面操作
              chores();
            }
          }
        });
      }
    });
  }

  // 处理更新
  function handleUpdate(row: any) {
    // 这里可以添加更新逻辑
    console.log(row);
  }

  // 处理删除
  function handleDelete(row: any) {
    ElMessageBox.confirm(
      `确认要删除设备关联编号为${row.id}的这条数据吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    )
      .then(() => {
        http
          .post(
            changeHttpLink(
              "index.php/device/deviceCorrelated/deviceCorrelated_delete"
            ),
            {
              data: { ids: row.id }
            }
          )
          .then((res: any) => {
            if (res.status === "success") {
              message("删除成功", { type: "success" });
              onSearch();
            } else {
              message(res.Message, { type: "error" });
            }
          })
          .catch(err => {
            message(err.message, { type: "error" });
          });
      })
      .catch(() => {
        // 取消操作
      });
  }

  // 处理重置
  function handleReset(row: any) {
    // 这里可以添加重置逻辑
    console.log(row);
  }

  // 处理角色
  function handleRole(row: any) {
    addDialog({
      title: "设备关联设置",
      width: "500px",
      contentRenderer: () => roleForm,
      props: {
        form: {
          deviceName: row.deviceName,
          roles: row.roles || []
        }
      },
      beforeSure: done => {
        done();
        onSearch();
      }
    });
  }

  // 处理分页大小变化
  function handleSizeChange(size: number) {
    pagination.pageSize = size;
    loadTableData();
  }

  // 取消选择
  function onSelectionCancel() {
    tableRef.value?.clearSelection();
  }

  // 处理当前页码变化
  function handleCurrentChange(current: number) {
    pagination.currentPage = current;
    loadTableData();
  }

  // 处理选择变化
  function handleSelectionChange(selection: any[]) {
    selectedNum.value = selection.length;
  }

  // 检测设备
  function deviceDetection() {
    return window.innerWidth < 1024;
  }

  // 挂载时加载数据
  onMounted(() => {
    loadTableData();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    selectedNum,
    pagination,
    buttonClass,
    deviceDetection,
    onSearch,
    resetForm,
    onbatchDel,
    openDialog,
    handleUpdate,
    handleDelete,
    handleReset,
    handleRole,
    handleSizeChange,
    onSelectionCancel,
    handleCurrentChange,
    handleSelectionChange
  };
}
